package com.zmx.gateway.config.currentlimit;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 限流的策略-用户
 * @ClassName: UserKeyResolverConfig
 * @Author zhaomxr
 * @Date 2022-01-18 18:00
 */
//@Configuration
public class UserKeyResolverConfig {

    private final static String COOKIE = "Cookies";

    //@Bean("userKeyResolver")
    KeyResolver userKeyResolver() {
        return exchange -> {
            String[] cookieList = exchange.getRequest().getHeaders().getFirst(COOKIE).split("; ");
            Map<String, String> cookieMap = new HashMap<String, String>(cookieList.length);
            Arrays.stream(cookieList).forEach(s -> {
                String[] split = s.split("=");
                if (!cookieMap.containsKey(split[0])) {
                    cookieMap.put(split[0].trim(), split[1].trim());
                }
            });
            return Mono.just(cookieMap.get("userId"));
        };
    }
}
